package com.odin.backgrounddownload;

import android.app.Activity;
import com.odin.backgrounddownload.downloader.SGBackGroundDownloadCallback;
import com.odin.backgrounddownload.downloader.SGBaseBackGroundDownload;
import com.odin.backgrounddownload.downloader.SGHmBackGroundDownload;

public class SGBackGroundDownloadManager {
    private static Activity s_UnityMainActivity;
    private static SGBaseBackGroundDownload s_BackGroudDownload;

    public static void Init(Activity activity, String cdnUrl, String persistentPath, SGBackGroundDownloadCallback callback)
    {
        s_UnityMainActivity = activity;
        s_BackGroudDownload = new SGHmBackGroundDownload(activity, cdnUrl, persistentPath, callback);
    }

    public static void SetDownloadParams(int maxCount, float silentIntervalTime, int silentBatchSize) {
        Logger.d("[SGBackGroundDownloadManager](SetMaxDownloadingCount)" + maxCount);
        s_BackGroudDownload.SetBackGroundDownloadParams(maxCount, silentIntervalTime, silentBatchSize);
    }

    public static void ForceDownload(String urlRelativePath, String saveRelativePath, long fileSize)
    {
        DownloadParam downloadParam = new DownloadParam(urlRelativePath, saveRelativePath, fileSize);
        s_BackGroudDownload.ForceDownload(downloadParam);
    }

    public static void AddDownload(byte[] param)
    {
        DownloadParam[] downloadParams = DeserializeDownloadParams(param);
        s_BackGroudDownload.AddDownload(downloadParams);
    }

    public static void StartDownload()
    {
        s_BackGroudDownload.StartDownload();
    }

    public static void PauseDownload()
    {
        s_BackGroudDownload.PauseDownload();
    }

    public static long GetDownloadedSize(){
        return s_BackGroudDownload.GetDownloadedSize();
    }

    public static long GetAllDownloadSize(){
        return s_BackGroudDownload.GetAllDownloadSize();
    }

    public static int QueryDownloadStatus(String urlRelativePath)
    {
        return s_BackGroudDownload.QueryDownloadStatus(urlRelativePath);
    }

    public static DownloadParam[] DeserializeDownloadParams(byte[] bytes) {

        ByteDataReader reader = new ByteDataReader(bytes);
        int length = reader.readInt();
        DownloadParam[] array = new DownloadParam[length];
        for (int i = 0; i < length; i++)
        {
            String urlRelativePath = reader.readString();
            String saveRelativePath = reader.readString();
            long fileSize = reader.readLong();
            array[i] = new DownloadParam(urlRelativePath, saveRelativePath, fileSize);
        }
        return array;
    }

}
